<template>
    <div class="ewe-mating-container">
        <!-- 操作按钮区域 -->
        <div class="operation-buttons">
            <button class="btn btn-primary">新增</button>
            <button class="btn btn-success" @click="saveData">保存</button>
            <button class="btn btn-info" @click="testBackend">测试后端</button>
            <button class="btn btn-danger">删除</button>
            <button class="btn btn-warning">+ 批量设置信息</button>
            <button class="btn btn-secondary">+ 批量选择种母</button>
            <div class="system-settings">
                <button class="btn-icon">⚙️</button>
                <button class="btn-icon">📋</button>
            </div>
        </div>

        <!-- 表单区域 -->
        <div class="form-section">
            <div class="form-row">
                <!-- <div class="form-item">
                    <label>* 负责人</label>
                    <select v-model="formData.responsibleFor" class="form-control">
                        <option value="">请选择</option>
                        <option value="">张三</option>
                        <option value="">李四</option>
                        <option value="">王五</option>
                         <-- 后端接口数据将填充这里 -->
                    <!-- </select>
                </div> --> 
                <div class="form-item">
                    <label>* 死亡日期</label>
                    <el-date-picker v-model="formData.deathdate" type="datetime" placeholder="选择日期时间" 
                        format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DDTHH:mm:ss.sssZ" />
                </div>  
                <div class="form-item">
                    <label>* 羊只类型</label>
                    <select v-model="formData.sheepType" class="form-control">
                        <option >请选择</option>
                        <option value="种公">种公</option>
                        <option value="种母">种母</option>
                        <option value="后裔">后裔</option>
                        <!-- <-- 后端接口数据将填充这里 --> 
                    </select>
                </div> 
                <div class="form-item">
                    <label>单据号</label>
                    <input type="text" class="form-control" v-model="formData.documentnumber" placeholder="..." />
                </div>
                <!-- <div class="form-item">
                    <label>栏位</label>
                    <input type="text" class="form-control" v-model="formData.column" placeholder="..." />
                </div> -->
                <!-- <div class="form-item">
                    <label>流水号</label>
                    <input type="text" class="form-control" v-model="formData.serialNumber" placeholder="..." />
                </div> -->
            </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>序号</th>
                        <th>* 羊只耳号</th>
                        <th>* 死亡原因</th>
                        <th>* 品种</th>
                        <th>* 性别</th>
                        <th>当前栋舍</th>
                        <th>当前栏位</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(row, index) in tableData" :key="index">
                        <td>{{ index + 1 }}</td>
                        <td>
                            <input type="text" class="form-control" v-model="row.earNumber" placeholder="请输入耳号" />
                        </td>
                        <td>
                            <input type="text" class="form-control" v-model="row.reason"
                                placeholder="请输入死亡原因" />
                        </td>
                        <td>
                            <input type="text" class="form-control" v-model="row.variety"
                                placeholder="请输入品种" />
                        </td>
                        <td>
                            <select class="form-control" v-model="row.sex">
                                <option >请选择</option>
                                <option value="公">公</option>
                                <option value="母">母</option>
                            </select>
                        </td>
                        <!-- <td>
                            <select class="form-control" v-model="row.ewematingEstrus">
                                <option value="">请选择</option>
                                <option value="nat1ural">自然交配</option>
                                <option value="artificial">人工授精</option>
                            </select>
                        </td> -->
                        <!-- <td>
                            <select class="form-control" v-model="row.ewematingRating">
                                <option value="">请选择</option>
                                <option value="1">1分</option>
                                <option value="2">2分</option>
                                <option value="3">3分</option>
                                <option value="4">4分</option>
                                <option value="5">5分</option>
                            </select>
                        </td> -->
                        <td>
                            <select class="form-control" v-model="row.building">
                                <option value="">请选择</option>
                                <option value="大羊舍">大羊舍</option>
                                <option value="配种舍">配种舍</option>
                                <option value="采购羊栋舍">采购羊栋舍</option>
                                <!-- 后端接口数据将填充这里 -->
                            </select>
                        </td>
                        <td>
                            <input type="text" class="form-control" v-model="row.column"
                                placeholder="请输入栏位" />
                        </td>
                        <!-- <td>
                            <input type="text" class="form-control" v-model="row.ewematingField" placeholder="请输入" />
                        </td> -->
                        <!-- <td>
                            <select class="form-control" v-model="row.eweTransferhouse">
                                <option value="">请选择</option>
                                <option value="1">大羊舍</option>
                                <option value="2">配种舍</option>
                                <option value="3">采购羊栋舍</option>
                                <-- 后端接口数据将填充这里 -->
                            <!-- </select>
                        </td> --> 
                        <!-- <td>
                            <input type="text" class="form-control" v-model="row.ewematingTransfer" placeholder="请输入" />
                        </td> -->
                        <!-- <td>
                            <select class="form-control" v-model="row.reproductiveStatus">
                                <option value="">请选择</option>
                                <option :value="true">已怀孕</option>
                                <option :value="false">未怀孕</option>
                            </select>
                        </td> -->
                        <!-- <td>
                            <input type="date" class="form-control" v-model="row.ewematingDateTime" />
                        </td>
                        <td>
                            <input type="number" class="form-control" v-model.number="row.ewematingWeight"
                                placeholder="0.00" step="0.01" />
                        </td> -->
                        <!-- <td>
                            <input type="text" class="form-control" v-model="row.remarks" placeholder="请输入备注" />
                        </td> -->
                    </tr>
                </tbody>
                <!-- <tfoot>
                    <tr>
                        <td colspan="13">合计</td>
                        <td>{{ totalWeight.toFixed(2) }}</td>
                    </tr>
                </tfoot> -->
            </table>
        </div>

        <!-- 增删行按钮 -->
        <div class="row-operations">
            <button class="btn btn-small btn-success" @click="addRow">+ 增行</button>
            <button class="btn btn-small btn-danger" @click="deleteRow" :disabled="tableData.length <= 0">- 删行</button>
        </div>

        <!-- 备注区域 -->
        <!-- <div class="remark-section">
            <label>备注</label>
            <textarea class="form-control" v-model="remark" placeholder="请输入备注信息" rows="2"></textarea>
        </div> -->
    </div>
</template>

<script  lang="ts" setup>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { ref, reactive } from 'vue';
import { Writes } from '../../Utils/axiosHelper';

// 定义表格行数据类型
interface TableRow {
    deathId: number,
    earNumber: string,
    reason: string,
    variety: string,
    sex: string,
    building: string,
    column: string
}

// 当前日期
const formData = reactive({
  deathdate: "",
  sheepType: "",
  documentnumber: "",
})

// 表格数据
const tableData = ref<TableRow[]>([
    {
      deathId: 0,
      earNumber: "",
      reason: "",
      variety: "",
      sex: "",
      building: "",
      column: ""
    }
]);

// 备注
const remark = ref('');

// 计算总重量
// const totalWeight = computed(() => {
//     return tableData.value.reduce((sum, row) => sum + (row.ewematingWeight || 0), 0);
// });

// 添加新行
const addRow = () => {
    const newRow: TableRow = {
        deathId: 0,
        earNumber: "",
        reason: "",
        variety: "",
        sex: "",
        building: "",
        column: ""
    };
    tableData.value.push(newRow);
};

// 删除最后一行
const deleteRow = () => {
    if (tableData.value.length > 0) {
        tableData.value.pop();
    }
};

// 测试后端连接
const testBackend = async () => {
    try {
        console.log('=== 测试后端连接 ===');
        
        // 测试不同的端点
        const testUrls = [
            'http://localhost:5008/api',
            'http://localhost:5008/api/Management',
            'http://localhost:5008/api/Management/CreateDeath',
            'http://localhost:5008/api/Management/GetDeaths',
            'http://localhost:5008/api/Test'
        ];
        
        for (const url of testUrls) {
            try {
                console.log(`测试URL: ${url}`);
                const response = await axios.get(url, {
                    timeout: 5000,
                    headers: {
                        'Accept': 'application/json'
                    }
                });
                console.log(`URL ${url} 测试成功:`, response.status, response.data);
                ElMessage.success(`后端连接成功 - ${url}`);
                return;
            } catch (urlError: any) {
                console.log(`URL ${url} 测试失败:`, urlError.response?.status || urlError.message);
            }
        }
        
        // 如果所有GET请求都失败，尝试POST请求
        console.log('尝试POST请求测试...');
        const testData = {
            deathdate: "2025-01-01T00:00:00.000Z",
            sheepType: "test",
            documentnumber: "test",
            deathsList: [{
                deathId: 0,
                earNumber: "test",
                reason: "test",
                variety: "test",
                sex: "test",
                building: "test",
                column: "test"
            }]
        };
        
        const postResponse = await axios.post('http://localhost:5008/api/Management/CreateDeath', testData, {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            timeout: 10000
        });
        
        console.log('POST测试成功:', postResponse.status, postResponse.data);
        ElMessage.success('后端POST接口测试成功');
        
    } catch (error: any) {
        console.log('=== 后端测试失败 ===');
        console.error('测试失败:', error);
        
        if (error.response) {
            console.log('错误响应状态:', error.response.status);
            console.log('错误响应数据:', error.response.data);
            ElMessage.error(`后端测试失败: ${error.response.status} - ${error.response.data?.message || '服务器错误'}`);
        } else if (error.request) {
            console.log('网络请求失败:', error.request);
            ElMessage.error('后端测试失败: 无法连接到服务器，请检查后端服务是否启动');
        } else {
            console.log('其他错误:', error.message);
            ElMessage.error(`后端测试失败: ${error.message}`);
        }
    }
};

// 保存数据到后端
const saveData = async () => {
    try {
        // 验证表单数据
        if (!formData.deathdate) {
            ElMessage.warning('请选择死亡日期');
            return;
        }
        if (!formData.sheepType) {
            ElMessage.warning('请选择羊只类型');
            return;
        }
        if (!formData.documentnumber) {
            ElMessage.warning('请输入单据号');
            return;
        }

        // 校验表格数据
        if (!tableData.value || tableData.value.length === 0) {
            ElMessage.warning('请至少添加一条死亡记录');
            return;
        }

        // 过滤有效数据（至少有一个字段不为空）
        const validRecords = tableData.value.filter(row => 
            row.earNumber || row.reason || row.variety || row.sex || row.building || row.column
        );

        if (validRecords.length === 0) {
            ElMessage.warning('请至少填写一条完整的死亡记录');
            return;
        }

        // 构建API请求数据
        const apiPayload = {
            deathdate: formData.deathdate, // 现在已经是ISO格式了
            sheepType: formData.sheepType,
            documentnumber: formData.documentnumber,
            deathsList: validRecords.map(row => ({
                deathId: row.deathId,
                earNumber: row.earNumber,
                reason: row.reason,
                variety: row.variety,
                sex: row.sex,
                building: row.building,
                column: row.column
            }))
        };

        console.log('发送到后端的数据:', JSON.stringify(apiPayload, null, 2));

        // 使用axios直接发送请求
        console.log('开始发送请求到:', 'http://localhost:5008/api/Management/CreateDeath');
        console.log('请求数据:', apiPayload);
        
        const response = await axios.post('http://localhost:5008/api/Management/CreateDeath', apiPayload, {
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            },
            timeout: 10000
        });
        
        console.log('后端响应状态:', response.status);
        console.log('后端响应数据:', response.data);
        console.log('完整响应:', response);

        if (response.status === 200) {
            // 检查响应数据中的成功标识
            if (response.data && (response.data.success === true || response.data.code === 200 || response.data.message === 'success' || response.data.code === 100)) {
                ElMessage.success(`保存成功，共保存${validRecords.length}条记录`);
                
                // 清空表单数据
                formData.deathdate = '';
                formData.sheepType = '';
                formData.documentnumber = '';
                
                // 重置表格数据
                tableData.value = [{
                    deathId: 0,
                    earNumber: "",
                    reason: "",
                    variety: "",
                    sex: "",
                    building: "",
                    column: ""
                }];
            } else {
                console.log('后端返回失败状态:', response.data);
                ElMessage.error(`保存失败: ${response.data?.message || response.data?.msg || '后端返回失败状态'}`);
            }
        } else {
            console.log('HTTP状态码不是200:', response.status);
            ElMessage.error(`保存失败，HTTP状态码: ${response.status}`);
        }
    } catch (error: any) {
        console.log('=== 请求异常详情 ===');
        console.error('保存失败:', error);
        console.log('错误类型:', typeof error);
        console.log('错误对象:', error);
        
        if (error.response) {
            // 服务器响应了错误状态码
            console.log('错误响应状态:', error.response.status);
            console.log('错误响应数据:', error.response.data);
            console.log('错误响应头:', error.response.headers);
            
            // 特别处理400错误，显示详细验证信息
            if (error.response.status === 400) {
                console.log('=== 400错误详细信息 ===');
                console.log('错误类型:', error.response.data?.type);
                console.log('错误标题:', error.response.data?.title);
                console.log('错误状态:', error.response.data?.status);
                console.log('验证错误:', error.response.data?.errors);
                console.log('追踪ID:', error.response.data?.traceId);
            }
            
            if (error.response.status === 404) {
                ElMessage.error('保存失败: API接口不存在(404)，请检查后端路由配置');
            } else if (error.response.status === 401) {
                ElMessage.error('保存失败: 未授权(401)，请检查认证信息');
            } else if (error.response.status === 400) {
                console.log('400错误详情:', error.response.data);
                if (error.response.data?.errors) {
                    // 显示具体的验证错误
                    const validationErrors = error.response.data.errors;
                    let errorMessage = '保存失败: 数据验证错误\n';
                    for (const field in validationErrors) {
                        errorMessage += `${field}: ${validationErrors[field].join(', ')}\n`;
                    }
                    ElMessage.error(errorMessage);
                } else {
                    ElMessage.error(`保存失败: 请求参数错误(400) - ${error.response.data?.title || error.response.data?.message || '请检查数据格式'}`);
                }
            } else if (error.response.status === 500) {
                ElMessage.error('保存失败: 服务器内部错误(500)');
            } else {
                ElMessage.error(`保存失败: ${error.response.status} - ${error.response.data?.message || error.response.data?.msg || '服务器错误'}`);
            }
        } else if (error.request) {
            // 请求已发出但没有收到响应
            console.log('网络请求失败:', error.request);
            ElMessage.error('保存失败: 网络连接异常，请检查后端服务是否启动在端口5008');
        } else if (error.code === 'ECONNABORTED') {
            // 请求超时
            console.log('请求超时:', error.message);
            ElMessage.error('保存失败: 请求超时，请检查网络连接');
        } else {
            // 其他错误
            console.log('其他错误:', error.message);
            ElMessage.error(`保存失败: ${error.message}`);
        }
    }
};
</script>

<style scoped>
.ewe-mating-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

/* 操作按钮区域 */
.operation-buttons {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 15px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.operation-buttons .btn {
    margin-right: 10px;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

.operation-buttons .btn-primary {
    background-color: #ff6b6b;
    color: white;
}

.operation-buttons .btn-success {
    background-color: #48dbfb;
    color: white;
}

.operation-buttons .btn-info {
    background-color: #feca57;
    color: white;
}

.operation-buttons .btn-danger {
    background-color: #ff9ff3;
    color: white;
}

.operation-buttons .btn-warning {
    background-color: #5f27cd;
    color: white;
}

.operation-buttons .btn-secondary {
    background-color: #54a0ff;
    color: white;
}

.operation-buttons .btn:hover {
    opacity: 0.8;
}

.system-settings {
    display: flex;
    gap: 10px;
}

.btn-icon {
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
}

/* 表单区域 */
.form-section {
    background-color: #fff;
    padding: 15px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.form-row {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

.form-item {
    display: flex;
    flex-direction: column;
    min-width: 200px;
    flex: 1;
}

.form-item label {
    margin-bottom: 5px;
    font-weight: 500;
    font-size: 14px;
}

.form-control {
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.form-control:focus {
    outline: none;
    border-color: #54a0ff;
    box-shadow: 0 0 0 2px rgba(84, 160, 255, 0.2);
}

/* 表格区域 */
.table-container {
    background-color: #fff;
    padding: 15px;
    margin-bottom: 20px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
    overflow-x: auto;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
}

.data-table th,
.data-table td {
    padding: 10px;
    text-align: left;
    border-bottom: 1px solid #eee;
}

.data-table th {
    background-color: #f8f9fa;
    font-weight: 600;
    font-size: 14px;
    white-space: nowrap;
}

.data-table input,
.data-table select {
    width: 100%;
    padding: 6px 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.data-table tfoot {
    font-weight: 600;
}

/* 增删行按钮 */
.row-operations {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.btn-small {
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 14px;
    transition: all 0.3s ease;
}

.btn-small:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

/* 备注区域 */
.remark-section {
    background-color: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.remark-section label {
    display: block;
    margin-bottom: 8px;
    font-weight: 500;
    font-size: 14px;
}

.remark-section textarea {
    width: 100%;
    resize: vertical;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .form-row {
        flex-direction: column;
    }

    .form-item {
        min-width: 100%;
    }

    .operation-buttons {
        flex-wrap: wrap;
    }

    .operation-buttons .btn {
        margin-bottom: 10px;
    }
}
</style>